package com.caigou.modules.forum.ui.market

import android.os.Bundle
import android.text.TextUtils
import androidx.activity.viewModels
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.caigou.comm.base.bean.AppBackgroundInfo
import com.caigou.comm.base.constants.AppConstants
import com.caigou.comm.base.constants.RouterPath
import com.caigou.comm.base.container.BaseActivity
import com.caigou.comm.base.ext.Resource
import com.caigou.comm.base.ext.observe
import com.caigou.comm.base.ext.showToast
import com.caigou.comm.base.widget.SpaceItemDecoration
import com.caigou.modules.forum.R
import com.caigou.modules.forum.adpter.MarketItemAdapter
import com.caigou.modules.forum.bean.PostBean
import com.caigou.modules.forum.databinding.ActivityMarketBinding
import com.caigou.modules.forum.viewmodel.MarketViewModel
import com.google.android.material.tabs.TabLayout
import dagger.hilt.android.AndroidEntryPoint

/**
 * @author #Suyghur.
 * Created on 2021/12/28
 */
@Route(path = RouterPath.Forum.PAGE_MARKET)
@AndroidEntryPoint
class MarketActivity : BaseActivity() {
    private lateinit var binding: ActivityMarketBinding
    private val marketViewModel: MarketViewModel by viewModels()

    private var page = 1
    private val limit = 10
    private var totalPage = 0

    private var superMaterialType = -1
    private val superMaterialNames = mutableListOf(
        "全部",
        "特码",
        "平肖",
        "生肖",
        "综合",
        "头数",
        "尾数",
        "大小单双",
        "波色",
        "五行",
        "特家野码",
        "杀码",
        "合数",
        "统计数",
        "码段"
    )

    private val mAdapter: MarketItemAdapter by lazy {
        MarketItemAdapter(mutableListOf())
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMarketBinding.inflate(layoutInflater)
        setContentView(binding.root)
        containerId = binding.marketLlContainer.id
        initView()
    }

    private fun initView() {
        ARouter.getInstance().inject(this)

        binding.marketSwipeRefreshLayout.run {
            setColorSchemeColors(resources.getColor(R.color.caigou_theme_color))
            setOnRefreshListener {
                page = 1
                fetchMarketList()
            }
        }

        mAdapter.loadMoreModule.run {
            setOnLoadMoreListener {
                mAdapter.loadMoreModule.isEnableLoadMore = true
                fetchMarketList()
            }
            isAutoLoadMore = true
            isEnableLoadMoreIfNotFullPage = false
        }
        binding.marketRecyclerView.run {
            layoutManager = LinearLayoutManager(this@MarketActivity)
            adapter = mAdapter
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(SpaceItemDecoration(this@MarketActivity))
        }

        mAdapter.setOnItemClickListener { adapter, view, position ->
            val postId = mAdapter.getItem(position).id
            ARouter.getInstance().build(RouterPath.Forum.PAGE_MARKET_POST)
                .withInt(AppConstants.POST_ID, postId)
                .navigation()
        }

        superMaterialNames.forEachIndexed { idx, value ->
            val tab = binding.marketTabLayout.newTab()
            tab.text = value
            binding.marketTabLayout.addTab(tab, idx)
        }

        binding.marketTabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                tab?.apply {
                    superMaterialType = position - 1
                    page = 1
                    fetchMarketList()
                }
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {
            }

            override fun onTabReselected(tab: TabLayout.Tab?) {
            }

        })

        binding.marketLlPublish.setOnClickListener {
            if (AppBackgroundInfo.instance.hasLogin) {
                ARouter.getInstance().build(RouterPath.Forum.PAGE_PUBLISH_POST)
                    .withInt(AppConstants.FORUM_TYPE, 6)
                    .navigation()
            } else {
                showToast("请您先登录")
            }
        }

        binding.marketTvBack.setOnClickListener {
            finish()
        }

        binding.marketIvSearch.setOnClickListener {
            ARouter.getInstance().build(RouterPath.Forum.PAGE_MARKET_SEARCH).navigation()
        }
        fetchMarketList()
    }

    override fun observeViewModel() {
        super.observeViewModel()
        observe(marketViewModel.marketListLiveData, ::handleGetMarketList)
    }

    private fun handleGetMarketList(result: Resource<PostBean>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.marketSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("获取猛料信息异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.marketSwipeRefreshLayout.isRefreshing = false
                if (result.data == null) {
                    return
                }
                totalPage = result.data!!.totalPage

                if (page == 1) {
                    mAdapter.setList(result.data!!.list)
                } else {
                    mAdapter.addData(result.data!!.list)
                }

                if (result.data!!.pageSize < limit) {
                    mAdapter.loadMoreModule.loadMoreEnd(false)
                } else {
                    mAdapter.loadMoreModule.loadMoreComplete()
                }

                if (page >= totalPage) {
                    mAdapter.loadMoreModule.loadMoreEnd(false)
                } else {
                    page++
                }
            }
        }
    }

    private fun fetchMarketList() {
        val userId = if (AppBackgroundInfo.instance.hasLogin) {
            AppBackgroundInfo.instance.userBean!!.userId
        } else {
            ""
        }
        marketViewModel.getMarketList(page, limit, superMaterialType, userId)
    }
}